$(function() {
	function searchParse(){
		var resultObj = {};
		var search = window.location.search;
		if(search && search.length > 1){
			var search = search.substring(1);
			var items = search.split('&');     
			for(var index = 0 ; index < items.length ; index++ ){   
				if(! items[index]){
					continue;
				}             
				var kv = items[index].split('='); 
				resultObj[kv[0]] = typeof kv[1] === "undefined" ? "":kv[1];
			}                
		} 
		return resultObj;
	}
	const query = searchParse()
	
	
	const E = window.wangEditor
	const editor = new E('#detail')
	editor.config.uploadImgShowBase64 = true
	editor.create()
	
	
	// 数据回填
	$.ajax({
		url: "http://120.27.209.174:1010/api/v1/posts_type",
		success(types) {
			$.ajax({
				url: `http://120.27.209.174:1010/api/v1/posts/${query.id}`,
				success(res) {
					console.log(res)
					$("[name=title]").val(res.title)
					$("[name=description]").val(res.description)
					$("[name=poster]").val(res.poster)
					$("[name=author]").val(res.author)
					
					// js设置editor的值
					editor.txt.html(res.detail)
					
					types.forEach(function(item) {
						if(res.type === item.type) {
							$("#type").append(`<option selected value="${item.type}">${item.text}</option>`)
						} else {
							$("#type").append(`<option value="${item.type}">${item.text}</option>`)	
						}
					})
				}
			})		
		}
	})
	
	function serializeObject(form) {
	   var o = {};
	   var a = $(form).serializeArray();
	   $.each(a, function() {
		   if (o[this.name]) {
			   if (!o[this.name].push) {
				   o[this.name] = [o[this.name]];
			   }
			   o[this.name].push(this.value || '');
		   } else {
			   o[this.name] = this.value || '';
		   }
	   });
	   return o;
	};
	
	// 表单验证
	$(".needs-validation").validate({
		focusInvalid: false,
		onkeyup: false,   
		submitHandler: function(form){
			// 序列化之后的数据
			const data = serializeObject(form)
			data.detail = editor.txt.html()
			console.log(data)
			// swal("Hello world!");
			swal({
			  title: "确认提交",
			  text: "你确定要提交修改吗？",
			  type: "warning",
			  showCancelButton: true,
			  confirmButtonColor: "#DD6B55",
			  confirmButtonText: "确定",
			  cancelButtonText: "取消",
			  closeOnConfirm: false
			}, function(){
				$.ajax({
					method: "PUT",
					url: `http://120.27.209.174:1010/api/v1/posts/${query.id}`,
					data: data,
					success(res) {
						swal("修改成功!", "文章修改成功!", "success");
						location.href = `./show.html?id=${query.id}`
					}
				})
				
			});
			
		},   
		rules:{
			title: {required:true, rangelength:[ 10, 30]},
			description: {required:true},
			poster: {required:true, url: true},
			author: {required:true},
			type: {required:true},
			detail: {required:true},
		},
	})
	
	
})